const advnwc = require('advnwc');
const permission = require('permission');
console.inspectEnable = true;

/**
 * 检测权限
 * @param {string[]} perms 检测的权限数组
 * @returns {boolean}
 */
function checkPerm(keys) {
  if (!keys || !keys.length) {
    return Promise.reject(false);
  }
  return new Promise((resolve, reject) => {
    const needCheckPerms = keys.reduce((res, item) => {
      res[item] = true;
      return res;
    }, {});
    permission.check(needCheckPerms, (res) => {
      console.log(`checkPerm(${JSON.stringify(keys)}):`, res)
      if (res) {
        resolve(true);
      } else {
        reject(false);
      }
    });
  });
}

/* 获取局域网和广域网中包含的网络接口信息 */
function getIfnames() {
  return new Promise((resolve, reject) => {
    advnwc.netifs(true, function (error, list) {
      if (error) {
        reject(error);
      } else {
        console.info('LAN port interface:', list);
        resolve(list[0]);
      }
    });
  }).then((ifname) => {
    return new Promise((resolve, reject) => {
      advnwc.netifs(false, function (error, list) {
        if (error) {
          reject(error);
        } else {
          console.info('WAN port interface:', list);
          resolve({ lan: ifname, wan: list[0] });
        }
      });
    });
  });
}

module.exports = {
  checkPerm,
  getIfnames,
};
